package servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    ServletContext的演示
 */
public class ServletContextDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取ServletContext对象
        ServletContext context=getServletContext();
        //2.常用方法的演示

        //获取全局配置参数:getInitParameter(String key) 根据key获取value
        String globalValue = context.getInitParameter("globalEncoding");
        System.out.println(globalValue);

        //获取应用的虚拟目录:getContextPath()
        String contextPath = context.getContextPath();
        System.out.println(contextPath);
        //根据虚拟目录获取绝对目录:getRealPath(String path)
        String realPath = context.getRealPath("/");
        System.out.println(realPath);

        //获取绝对路径
        String realPath1 = context.getRealPath("/b.txt");
        System.out.println(realPath1);

        String realPath2 = context.getRealPath("/WEB-INF/c.txt");
        System.out.println(realPath2);

        String realPath3 = context.getRealPath("/WEB-INF/classes/a.txt");
        System.out.println(realPath3);


        //设置共享数据
        context.setAttribute("username","zhangsan");
        //删除共享数据
        context.removeAttribute("username");


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
